﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using MSCacheSample.Infrastructure;
using MSCacheSample.Tests;

namespace MSCacheSample.Controllers
{
    [Produces("application/json")]
    [Route("api/Tests/[action]")]
    public class TestsController : Controller
    {
        private readonly IMemoryCache _memoryCache;
        private readonly ITestService _testService;
        public TestsController(IMemoryCache memoryCache,
            ITestService testService)
        {
            _memoryCache = memoryCache;
            _testService = testService;
        }
        [HttpGet]
        public IActionResult Get()
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            _testService.Test();
            sw.Stop();
            string name = string.Empty;
            string cacheKey = Guid.NewGuid().ToString("N");
            var b = _memoryCache.TryGetValue(cacheKey, out name);
            if (!b)
            {
                name = "My name is ZhangJian.";
                _memoryCache.Set(cacheKey, name, DateTimeOffset.Now.AddSeconds(3));
            }
            var oldVal = _memoryCache.Get(cacheKey);
            Thread.Sleep(3000);
            var newVal = _memoryCache.Get(cacheKey);
            return Json(new { Old = oldVal, New = newVal,ExpireTime=sw.ElapsedMilliseconds });
        }
        [HttpGet]
        public IActionResult Get2()
        {
            var guid = Guid.NewGuid().ToString("N");
            string name = _memoryCache.GetOrCreate(guid, entry =>
           {
               entry.Value = guid;
               entry.AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(3);
               return guid.ToString();
           });
            var oldVal = _memoryCache.Get(guid);
            Thread.Sleep(3000);
            var newVal = _memoryCache.Get(guid);
            return Json(new { Old = oldVal, New = newVal });
        }
        [HttpGet]
        public IActionResult Get3()
        {
            string name = string.Empty;
            var b = _memoryCache.TryGetValue("name", out name);
            if (!b)
            {
                name = "ZhangJian";
                var entry = _memoryCache.CreateEntry("name");//Is disposed , cannot set cache.
                entry.Value = name;
            }
            return Json(name);
        }
        [HttpGet]
        public IActionResult Get4()
        {
            string name = string.Empty;
            var b = _memoryCache.TryGetValue("name", out name);
            if (!b)
            {
                name = "ZhangJian";
                using (var entry = _memoryCache.CreateEntry("name"))
                {
                    entry.Value = name;
                };
            }
            return Json(name);
        }
    }
}